package gui.panel_new.evaluation.professor;

import enums.FileFilterEnum;
import enums.TestPanelEnum;
import enums.TextBundleEnum;
import enums.URLEnum;
import gui.panel_new.evaluation.exeptions.ExerciseNotBuiltException;
import gui.panel_new.evaluation.exeptions.PunctuationZeroException;
import j_util.Utiles;
import misc.BundlesProvider;
import model.eval.TestExcercise;
import model.eval.TestExerciseMChoice;
import model.mchoice.MCItem;
import model.mchoice.MCItemSet;

import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ResourceBundle;
/*

    This file is part of Logica-Logike.

    Logica-Logike is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation version 3 of the License.

    Logica-Logike is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Logica-Logike.  If not, see <http://www.gnu.org/licenses/>.

 */
/**
 * Esta clase extiende de CreateExcercisePanel; tiene como proposito proveer la interfaz grafica a la creacion
 * de multiple choice;
 *
 * @author Jose Martin Rozanec;
 */
public class CreateMChoicePanel extends CreateExercisePanel {
    private JLabel questionLabel;
    private JTextField questionTextField;
    private JLabel answersLabel;
    private JLabel firstAnswerLabel;
    private JLabel secondAnswerLabel;
    private JLabel thirdAnswerLabel;
    private JLabel fourthAnswerLabel;
    private JLabel fifthAnswerLabel;
    private JLabel sixthAnswerLabel;
    private JTextField firstAnswerTextField;
    private JTextField secondAnswerTextField;
    private JTextField thirdAnswerTextField;
    private JTextField fourthAnswerTextField;
    private JTextField fifthAnswerTextField;
    private JTextField sixthAnswerTextField;
    private JLabel correctLabel;
    private JCheckBox correct1;
    private JCheckBox correct2;
    private JCheckBox correct3;
    private JCheckBox correct4;
    private JCheckBox correct5;
    private JCheckBox correct6;
    private JLabel addsPoints;
    private JLabel substractPoints;
    private JTextField addsPointsField;
    private JTextField substractPointsField;
    private JButton addQuestionButton;
    private JButton resetQuestionButton;
    private JTextArea fullQuestionaireTextArea;
    private JTextField questionsQuantityTextField;
    private JCheckBox fixedPunctuationCheckBox;
    private JTextField fixedPunctuationField;
    private JCheckBox oneAnswerPerQuestionCheckBox;
    private JTextField substractProportionalityTextField;
    private JButton createExcerciseButton;
    private ButtonGroup buttonGroup;
    private JPanel questionsPanel;
    private JRadioButton radioButton3;
    private JRadioButton radioButton4;
    private JRadioButton radioButton5;
    private JRadioButton radioButton6;
    private ResourceBundle textBundle;

    private MCItemSet mcItemSet;
    private int answers;

    private boolean resetMode;

    /**
     * Constructor;
     *
     * @param saveButton;
     * @param openButton;
     * @param fileChooser;
     */
    public CreateMChoicePanel(JButton saveButton, JButton openButton, JFileChooser fileChooser) {
        this.saveButton = saveButton;
        this.openButton = openButton;
        this.fileChooser = fileChooser;
        fileFilter = FileFilterEnum.MCF;
        testPanelEnum = TestPanelEnum.MULTIPLE_CHOICE;
        answers = 4;
        mcItemSet = new MCItemSet();
        initComponents();
        initGUI();
    }

    /**
     * Metodo responsable de la inicializacion de los componentes;
     */
    private void initComponents() {
        resetMode = false;
        textBundle = BundlesProvider.getBundle(URLEnum.TEXT_BUNDLE);
        questionLabel = new JLabel(textBundle.getString(TextBundleEnum.PREGUNTA.toString()));
        questionTextField = new JTextField(44);
        answersLabel = new JLabel(textBundle.getString(TextBundleEnum.ANSWERS.toString()));
        firstAnswerLabel = new JLabel("A- ");
        secondAnswerLabel = new JLabel("B- ");
        thirdAnswerLabel = new JLabel("C- ");
        fourthAnswerLabel = new JLabel("D- ");
        fifthAnswerLabel = new JLabel("E- ");
        sixthAnswerLabel = new JLabel("F- ");
        firstAnswerTextField = new JTextField(25);
        secondAnswerTextField = new JTextField(25);
        thirdAnswerTextField = new JTextField(25);
        fourthAnswerTextField = new JTextField(25);
        fifthAnswerTextField = new JTextField(25);
        sixthAnswerTextField = new JTextField(25);
        correctLabel = new JLabel(textBundle.getString(TextBundleEnum.CORRECTA.toString()));
        correct1 = new JCheckBox();
        correct2 = new JCheckBox();
        correct3 = new JCheckBox();
        correct4 = new JCheckBox();
        correct5 = new JCheckBox();
        correct6 = new JCheckBox();
        addsPoints = new JLabel(textBundle.getString(TextBundleEnum.SUMA.toString()));
        substractPoints = new JLabel(textBundle.getString(TextBundleEnum.RESTA.toString()));
        addsPointsField = new JTextField(7);
        addsPointsField.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent e) {
                if (!addsPointsField.getText().equals("")) {
                    double substract = Double.parseDouble(substractProportionalityTextField.getText());
                    substractPointsField.setText("" + (int) (substract * Integer.parseInt(addsPointsField.getText())));
                }
            }
        });
        substractPointsField = new JTextField(7);
        substractPointsField.setEditable(false);
        addQuestionButton = new JButton(textBundle.getString(TextBundleEnum.AGREGAR_PREGUNTA.toString()));
        resetQuestionButton = new JButton(textBundle.getString(TextBundleEnum.RESETEAR_PREGUNTA.toString()));
        fullQuestionaireTextArea = new JTextArea(8, 48);// rows;columns
        questionsQuantityTextField = new JTextField(14);//32
        fixedPunctuationCheckBox = new JCheckBox(
                textBundle.getString(TextBundleEnum.FIXED_PUNCTUATION.toString()));
        fixedPunctuationCheckBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fixedPunctuationField.setEditable(fixedPunctuationCheckBox.isSelected());
            }
        });
        fixedPunctuationField = new JTextField(11);
        oneAnswerPerQuestionCheckBox = new JCheckBox(textBundle.getString(
                TextBundleEnum.ONE_ANSWER_PER_QUESTION.toString()));
        oneAnswerPerQuestionCheckBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                mcItemSet.setOneCorrectAnswerOnly(oneAnswerPerQuestionCheckBox.isSelected());
            }
        });
        substractProportionalityTextField = new JTextField(4);//22
        substractProportionalityTextField.setToolTipText(
                textBundle.getString(
                        TextBundleEnum.SUBSTRACT_PER_QUESTION_PROPORTIONALITY_TOOLTIP.toString()));
        createExcerciseButton = new JButton(textBundle.getString(
                TextBundleEnum.CREATE_EXCERCISE.toString()));
        buttonGroup = new ButtonGroup();
        questionsPanel = new JPanel();
        radioButton3 = new JRadioButton("3");
        radioButton4 = new JRadioButton("4");
        radioButton5 = new JRadioButton("5");
        radioButton6 = new JRadioButton("6");
        addButtonsActionListeners();
        reset();

    }

    /**
     * Metodo que agrupa los metodos que realizan el layout de los componentes visuales;
     */
    private void initGUI() {
        setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        add(createMCItemSetOptionsPanel(), gridBagConstraints);
        gridBagConstraints.gridy = 1;
        add(createQuestionCreationPanel(), gridBagConstraints);
        enableQuestionsPanel(false);
    }

    /**
     * Layout de los componentes referidos a las opciones de un conjunto de preguntas multiple choice;
     *
     * @return
     */
    private JPanel createMCItemSetOptionsPanel() {
        int x = 0;
        int y = 0;
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY),
                textBundle.getString(TextBundleEnum.MULTIPLE_CHOICE_TEST_OPTIONS.toString())));
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        JPanel auxPanel1 = new JPanel();
        auxPanel1.setLayout(new GridBagLayout());
        gridBagConstraints.gridwidth = 6;//5
        auxPanel1.add(new JLabel(textBundle.getString(
                TextBundleEnum.QUESTIONS_QUANTITY.toString()) + ": "), gridBagConstraints);
        x = 6;//5
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridwidth = 9;//10
        auxPanel1.add(questionsQuantityTextField, gridBagConstraints);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 30;
        panel.add(auxPanel1, gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridwidth = 22;//11
        JPanel auxPanel2 = new JPanel();
        auxPanel2.add(fixedPunctuationCheckBox);
        auxPanel2.add(fixedPunctuationField);
        panel.add(auxPanel2, gridBagConstraints);//fixedPunctuationCheckBox
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridwidth = 17;//8
        panel.add(oneAnswerPerQuestionCheckBox, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridwidth = 17;//8
        JPanel auxPanel3 = new JPanel(new GridBagLayout());
        auxPanel3.add(new JLabel(textBundle.getString(
                TextBundleEnum.SUBSTRACT_PER_QUESTION_PROPORTIONALITY.toString()) + ": "), gridBagConstraints);
        x = 17;//8
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridwidth = 13;//7
//        substractProportionalityTextField=new JTextField(22); //15
        auxPanel3.add(substractProportionalityTextField, gridBagConstraints);
        gridBagConstraints.gridwidth = 30;
        gridBagConstraints.gridx = 0;
        panel.add(auxPanel3, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        panel.add(createExcerciseButton, gridBagConstraints);
        //cantidad de preguntas, puntuacion proporcional, si existe una respuesta estricta por pregunta
        return panel;
        //ver posibilidad de revisar las preguntas...
    }

    /**
     * Layout para la creacion de cada una de las preguntas del multiple choice set;
     *
     * @return
     */
    private JPanel createQuestionCreationPanel() {
        int x = 0;
        int y = 0;
        questionsPanel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        fullQuestionaireTextArea.setEditable(false);
        questionsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
                textBundle.getString(TextBundleEnum.CREAR_PREGUNTA.toString()) + " 1 " +
                        textBundle.getString(TextBundleEnum.DE.toString()) + " " + questionsQuantityTextField.getText()));
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        questionsPanel.add(questionLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        gridBagConstraints.gridwidth = 3;
        questionsPanel.add(questionTextField, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridx = --x;
        gridBagConstraints.gridwidth = 2;
        questionsPanel.add(answersLabel, gridBagConstraints);
        x = 2;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridwidth = 1;
        questionsPanel.add(correctLabel, gridBagConstraints);
        gridBagConstraints.gridheight = 5;//3
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(createSidePanel(), gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridheight = 1;
        questionsPanel.add(firstAnswerLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(firstAnswerTextField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(correct1, gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        questionsPanel.add(secondAnswerLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(secondAnswerTextField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(correct2, gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        questionsPanel.add(thirdAnswerLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(thirdAnswerTextField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(correct3, gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        questionsPanel.add(fourthAnswerLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(fourthAnswerTextField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(correct4, gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        questionsPanel.add(fifthAnswerLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(fifthAnswerTextField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(correct5, gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        questionsPanel.add(sixthAnswerLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(sixthAnswerTextField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(correct6, gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridwidth = 4;
        questionsPanel.add(createButtonsPanel(), gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridheight = 6;
        questionsPanel.add(createFullQuestionairePanel(), gridBagConstraints);
        clearAllFields();
        return questionsPanel;
    }

    /**
     * Creacion del panel que muestra el puntaje por pregunta;
     *
     * @return JPanel - panel que contiene los fields y labels que indican los puntajes correspondientes;
     */
    private JPanel createScoringPanel() {
        JPanel scoringPanel = new JPanel();
        scoringPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.GRAY),
                textBundle.getString(TextBundleEnum.PUNTAJE.toString())));
        scoringPanel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        scoringPanel.add(addsPoints, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        scoringPanel.add(addsPointsField, gridBagConstraints);
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridx = 0;
        scoringPanel.add(substractPoints, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        scoringPanel.add(substractPointsField, gridBagConstraints);
        return scoringPanel;
    }

    /**
     * Creacion de un panel que contiene los botones de agregar pregunta y de reset;
     *
     * @return JPanel;
     */
    private JPanel createButtonsPanel() {
        JPanel buttonsPanel = new JPanel();
        buttonsPanel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(0, 25, 0, 25);
        gridBagConstraints.gridx = 0;
        buttonsPanel.add(addQuestionButton, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        buttonsPanel.add(resetQuestionButton, gridBagConstraints);
        return buttonsPanel;
    }

    /**
     * Panel que agrupa los radio buttons que permiten determinar la cantidad de respuestas para la pregunta
     * en cuestion;
     *
     * @return JPanel;
     */
    private JPanel createQuantityAnswersPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        int x = 0;
        int y = 0;
        JLabel answersToQuestionLabel = new JLabel(textBundle.getString(TextBundleEnum.ANSWERS_QUANTITY.toString()));
        ButtonGroup buttonGroup = new ButtonGroup();
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridwidth = 4;
        panel.add(answersToQuestionLabel, gridBagConstraints);
        gridBagConstraints.gridwidth = 1;
        gridBagConstraints.gridy = ++y;
        addRadioButtonListeners();
        buttonGroup.add(radioButton3);
        buttonGroup.add(radioButton4);
        buttonGroup.add(radioButton5);
        buttonGroup.add(radioButton6);
        panel.add(radioButton3, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        gridBagConstraints.gridx = ++x;
        gridBagConstraints.gridx = ++x;
        gridBagConstraints.gridwidth = 1;
        panel.add(radioButton4, gridBagConstraints);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridwidth = 1;
        panel.add(radioButton5, gridBagConstraints);
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridwidth = 1;
        panel.add(radioButton6, gridBagConstraints);
        return panel;
    }

    /**
     * Panel que agrupa los paneles de puntaje y de cantidad de respuestas que tendra la pregunta en cuestion;
     *
     * @return
     */
    private JPanel createSidePanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEtchedBorder());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridheight = 3;
        panel.add(createScoringPanel(), gridBagConstraints);
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridheight = 2;
        panel.add(createQuantityAnswersPanel(), gridBagConstraints);
        return panel;
    }

    /**
     * JScrollPane en el que se muestran todas las preguntas agregadas hasta el momento;
     *
     * @return
     */
    private JScrollPane createFullQuestionairePanel() {
        JScrollPane scrollPane = new JScrollPane(fullQuestionaireTextArea);
        scrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),
                textBundle.getString(TextBundleEnum.CUESTIONARIO_CREADO.toString())));
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        return scrollPane;
    }

    /**
     * Agrega listeners a los botones;
     */
    private void addButtonsActionListeners() {
        addQuestionButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                boolean passed = performQuestionCheckings();
                if (passed) {
                    MCItem item = new MCItem(answers);
                    item.setQuestion(questionTextField.getText());
                    item.setSolutions(firstAnswerTextField.getText(), 1);
                    item.setSolutionStatus(correct1.isSelected(), 1);
                    item.setSolutions(secondAnswerTextField.getText(), 2);
                    item.setSolutionStatus(correct2.isSelected(), 2);
                    item.setSolutions(thirdAnswerTextField.getText(), 3);
                    item.setSolutionStatus(correct3.isSelected(), 3);
                    switch (answers) {
                        case 6:
                            item.setSolutions(sixthAnswerTextField.getText(), 6);
                            item.setSolutionStatus(correct6.isSelected(), 6);
                        case 5:
                            item.setSolutions(fifthAnswerTextField.getText(), 5);
                            item.setSolutionStatus(correct5.isSelected(), 5);
                        case 4:
                            item.setSolutions(fourthAnswerTextField.getText(), 4);
                            item.setSolutionStatus(correct4.isSelected(), 4);
                    }

                    item.setCorrectPunctuation(Integer.parseInt(addsPointsField.getText()));
                    item.setIncorrectPunctuation(Integer.parseInt(substractPointsField.getText()));
                    mcItemSet.addMCItem(item);
                    manageQuestionPanelBorder();
                    clearAllFields();
                    fullQuestionaireTextArea.setText(mcItemSet.toString());
                    questionTextField.requestFocus();
                }
            }
        });

        resetQuestionButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                clearAllFields();
            }
        });

        createExcerciseButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (resetMode) {
                    reset();
                } else {
                    if (performMCParametersCheckings()) {
                        enableQuestionsPanel(true);
                        enableMCOptionsPanel(false);
                        manageButtonGroup();
                        managePointsFields();
                        clearAllFields();
                        enableAnswerTextFields(true, true, true, true, false, false);
                        manageQuestionPanelBorder();
                    }
                }
            }
        });
    }

    /**
     * Agrega listeners a los radioButtons;
     */
    private void addRadioButtonListeners() {
        radioButton3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                enableAnswerTextFields(true, true, true, false, false, false);
                answers = 3;
            }
        });
        radioButton4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                enableAnswerTextFields(true, true, true, true, false, false);
                answers = 4;
            }
        });
        radioButton5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                enableAnswerTextFields(true, true, true, true, true, false);
                answers = 5;
            }
        });
        radioButton6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                enableAnswerTextFields(true, true, true, true, true, true);
                answers = 6;
            }
        });
    }

    /**
     * Permite habilitar o desabilitar los textFields de respuestas a la pregunta de multiple choice formulada;
     *
     * @param first;
     * @param second;
     * @param third;
     * @param fourth;
     * @param fifth;
     * @param sixth;
     */
    private void enableAnswerTextFields(boolean first, boolean second, boolean third, boolean fourth,
                                        boolean fifth, boolean sixth) {
        firstAnswerTextField.setEnabled(first);
        correct1.setEnabled(first);
        secondAnswerTextField.setEnabled(second);
        correct2.setEnabled(second);
        thirdAnswerTextField.setEnabled(third);
        correct3.setEnabled(third);
        fourthAnswerTextField.setEnabled(fourth);
        correct4.setEnabled(fourth);
        fifthAnswerTextField.setEnabled(fifth);
        correct5.setEnabled(fifth);
        sixthAnswerTextField.setEnabled(sixth);
        correct6.setEnabled(sixth);
    }

    /**
     * Administra la logica de la agrupacion de los checkBoxes (correcto) en un buttonGroup, de acuerdo si se
     * permite que la pregunta tenga una respuesta o varias posibles;
     */
    private void manageButtonGroup() {
        if (oneAnswerPerQuestionCheckBox.isSelected()) {
            buttonGroup.add(correct1);
            buttonGroup.add(correct2);
            buttonGroup.add(correct3);
            buttonGroup.add(correct4);
            buttonGroup.add(correct5);
            buttonGroup.add(correct6);
        } else {
            buttonGroup.remove(correct1);
            buttonGroup.remove(correct2);
            buttonGroup.remove(correct3);
            buttonGroup.remove(correct4);
            buttonGroup.remove(correct5);
            buttonGroup.remove(correct6);
        }
    }

    /**
     * Administra la habilitacion o no de los textFields de puntaje;
     */
    private void managePointsFields() {
        if (fixedPunctuationCheckBox.isSelected()) {
            addsPointsField.setEditable(false);
            substractPointsField.setEditable(false);
        }
    }

    /**
     * Borra el texto de todos los fields;
     */
    private void clearAllFields() {
        questionTextField.setText("");
        firstAnswerTextField.setText("");
        secondAnswerTextField.setText("");
        thirdAnswerTextField.setText("");
        fourthAnswerTextField.setText("");
        fifthAnswerTextField.setText("");
        sixthAnswerTextField.setText("");
        addsPointsField.setText("0");
        substractPointsField.setText("0");
        if (oneAnswerPerQuestionCheckBox.isSelected()) {
            correct1.setSelected(true);
        }
        if (fixedPunctuationCheckBox.isSelected()) {
            addsPointsField.setText(fixedPunctuationField.getText());
            double substract = Double.parseDouble(substractProportionalityTextField.getText());
            substractPointsField.setText("" + (int) (substract * Integer.parseInt(fixedPunctuationField.getText())));
        }
    }

    /**
     * Realiza los chequeos necesarios para agregar la pregunta al conjunto de preguntas;
     *
     * @return boolean - true si paso las condiciones para ser agregado, falso en caso contrario;
     */
    private boolean performQuestionCheckings() {
        if (questionTextField.getText().equals("") || firstAnswerTextField.getText().equals("") ||
                secondAnswerTextField.getText().equals("") || thirdAnswerTextField.getText().equals("") ||
                performCheckingsAux() || addsPointsField.getText().equals("") ||
                substractPointsField.getText().equals("")) {
            JOptionPane.showMessageDialog(CreateMChoicePanel.this,
                    textBundle.getString(TextBundleEnum.WARNING_COMPLETAR_DATOS_MCHOICE.toString()),
                    "", JOptionPane.WARNING_MESSAGE);
            return false;
        } else {
            if (Integer.parseInt(addsPointsField.getText()) == 0) {
                JOptionPane.showMessageDialog(CreateMChoicePanel.this,
                        textBundle.getString(TextBundleEnum.WARNING_SUMA_CERO.toString()),
                        "", JOptionPane.WARNING_MESSAGE);
                return false;
            }
        }
        return true;
    }

    /**
     * Auxiliar para realizar el chequeo de las preguntas;
     *
     * @return
     */
    private boolean performCheckingsAux() {
        switch (answers) {
            case 4:
                return fourthAnswerTextField.getText().equals("");
            case 5:
                return fourthAnswerTextField.getText().equals("") || fifthAnswerTextField.getText().equals("");
            case 6:
                return fourthAnswerTextField.getText().equals("") ||
                        fifthAnswerTextField.getText().equals("") ||
                        sixthAnswerTextField.getText().equals("");
        }
        return false;
    }

    /**
     * Chequea los parametros de multiple choice;
     *
     * @return boolean - true si paso los chequeos, false caso contrario;
     */
    private boolean performMCParametersCheckings() {
        substractProportionalityTextField.setText(substractProportionalityTextField.getText().replace(",", "."));
        if (questionsQuantityTextField.getText().equals("") ||
                substractProportionalityTextField.getText().equals("")) {
            JOptionPane.showMessageDialog(CreateMChoicePanel.this,
                    textBundle.getString(TextBundleEnum.WARNING_COMPLETAR_DATOS.toString()),
                    "", JOptionPane.WARNING_MESSAGE);
        } else {
            try {
                if (Integer.parseInt(questionsQuantityTextField.getText()) < 1) {
                    JOptionPane.showMessageDialog(CreateMChoicePanel.this,
                            textBundle.getString(TextBundleEnum.WARNING_CANTIDAD_PREGUNTAS_POSITIVO_MAYOR_UNO.toString()) + "!",
                            "", JOptionPane.WARNING_MESSAGE);
                    return false;
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(CreateMChoicePanel.this,
                        textBundle.getString(TextBundleEnum.WARNING_CANTIDAD_PREGUNTAS_ENTERO.toString()) + "!",
                        "", JOptionPane.WARNING_MESSAGE);
                return false;
            }
            if (Double.parseDouble(substractProportionalityTextField.getText()) > 1 ||
                    Double.parseDouble(substractProportionalityTextField.getText()) < 0) {
                JOptionPane.showMessageDialog(CreateMChoicePanel.this,
                        textBundle.getString(TextBundleEnum.WARNING_PROPORCIONALIDAD_ENTRE_CERO_UNO.toString()) + "!",
                        "", JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (fixedPunctuationCheckBox.isSelected()) {
                if (fixedPunctuationField.getText().equals("")) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            textBundle.getString(TextBundleEnum.WARNING_COMPLETAR_DATOS.toString()),
                            "", JOptionPane.WARNING_MESSAGE);
                    return false;
                } else {
                    try {
                        if (Integer.parseInt(fixedPunctuationField.getText()) < 1) {
                            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                    textBundle.getString(TextBundleEnum.WARNING_SUMAR_POSITIVO.toString()) + "!",
                                    "", JOptionPane.WARNING_MESSAGE);
                            return false;
                        }
                    } catch (NumberFormatException e) {
                        JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                textBundle.getString(TextBundleEnum.WARNING_SUMAR_ENTERO.toString()) + "!",
                                "", JOptionPane.WARNING_MESSAGE);
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * Permite habilitar / desabilitar el panel que sirve para crear y agregar las preguntas;
     *
     * @param enable - boolean;
     */
    private void enableQuestionsPanel(boolean enable) {
        fullQuestionaireTextArea.setEnabled(enable);
        correct1.setEnabled(enable);
        correct2.setEnabled(enable);
        correct3.setEnabled(enable);
        correct4.setEnabled(enable);
        correct5.setEnabled(enable);
        correct6.setEnabled(enable);
        firstAnswerTextField.setEnabled(enable);
        secondAnswerTextField.setEnabled(enable);
        thirdAnswerTextField.setEnabled(enable);
        fourthAnswerTextField.setEnabled(enable);
        fifthAnswerTextField.setEnabled(enable);
        sixthAnswerTextField.setEnabled(enable);
        addQuestionButton.setEnabled(enable);
        resetQuestionButton.setEnabled(enable);
        questionTextField.setEnabled(enable);
        substractPointsField.setEnabled(enable);
        addsPointsField.setEnabled(enable);
        radioButton3.setEnabled(enable);
        radioButton4.setEnabled(enable);
        radioButton5.setEnabled(enable);
        radioButton6.setEnabled(enable);
    }

    /**
     * Permite habilitar o desabilitar el panel con las opciones de multiple choice;
     *
     * @param enable
     */
    private void enableMCOptionsPanel(boolean enable) {
        questionsQuantityTextField.setEnabled(enable);
        substractProportionalityTextField.setEnabled(enable);
        fixedPunctuationCheckBox.setEnabled(enable);
        fixedPunctuationField.setEnabled(enable);
        oneAnswerPerQuestionCheckBox.setEnabled(enable);
        resetMode = !enable;
        if (resetMode) {
            createExcerciseButton.setText(textBundle.getString(TextBundleEnum.RESETEAR_EJERCICIO.toString()));
        } else {
            createExcerciseButton.setText(textBundle.getString(TextBundleEnum.CREATE_EXCERCISE.toString()));
        }        
    }

    /**
     * Administra el borde del panel de creacion de preguntas, informando de la
     * pregunta corriente sobre el total de preguntas;
     */
    private void manageQuestionPanelBorder() {
        if (mcItemSet.getMCItems().size() < Integer.parseInt(questionsQuantityTextField.getText())) {
            questionsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
                    textBundle.getString(TextBundleEnum.CREAR_PREGUNTA.toString()) +
                            " " + (mcItemSet.getMCItems().size() + 1) + " " +
                            textBundle.getString(TextBundleEnum.DE.toString()) + " " +
                            questionsQuantityTextField.getText()));
        } else {
            enableMCOptionsPanel(true);
            enableQuestionsPanel(false);
        }
    }

    public TestExcercise getExercise() throws ExerciseNotBuiltException, PunctuationZeroException {
        if (mcItemSet.getMCItems().size() < Integer.parseInt(questionsQuantityTextField.getText())
                || addsPointsField.getText().equals("") || substractPointsField.getText().equals("")) {
            throw new ExerciseNotBuiltException();
        }
        if (Integer.parseInt(addsPointsField.getText()) == 0) {
            throw new PunctuationZeroException();
        }
        TestExcercise testExercise = new TestExerciseMChoice();
        testExercise.setExerciseData(mcItemSet);
        testExercise.setStudentsSolution(mcItemSet.getDefaultSet());
        return testExercise;
    }

    public void setExercise(TestExcercise testExcercise) { //todo terminar de setear los parametros...
        this.mcItemSet = (MCItemSet) testExcercise.getExcerciseData();
        fullQuestionaireTextArea.setText(mcItemSet.toString());
        MCItem item = mcItemSet.getMCItems().get(0);
        addsPointsField.setText("" + item.getCorrectPunctuation());
        substractPointsField.setText("" + item.getIncorrectPunctuation());
        questionTextField.setText(item.getQuestion());
        String[] solutions = item.getSolutions();
        System.out.println("CreateMChoicePanel:- solutionSize: " + solutions.length);
        firstAnswerTextField.setText(solutions[0]);
        secondAnswerTextField.setText(solutions[1]);
        thirdAnswerTextField.setText(solutions[2]);
        setSelectedRadioButtons(radioButton3, radioButton4, radioButton5, radioButton6, 3);
        if (solutions.length > 3) {
            fourthAnswerTextField.setText(solutions[3]);
            setSelectedRadioButtons(radioButton3, radioButton4, radioButton5, radioButton6, 4);
            enableTextFields(fourthAnswerTextField, fifthAnswerTextField, sixthAnswerTextField, 4);
            enableCheckBoxes(correct4, correct5, correct6, 4);
        }
        if (solutions.length > 4) {
            fifthAnswerTextField.setText(solutions[4]);
            setSelectedRadioButtons(radioButton3, radioButton4, radioButton5, radioButton6, 5);
            enableTextFields(fourthAnswerTextField, fifthAnswerTextField, sixthAnswerTextField, 5);
            enableCheckBoxes(correct4, correct5, correct6, 5);
        }
        if (solutions.length > 5) {
            sixthAnswerTextField.setText(solutions[5]);
            setSelectedRadioButtons(radioButton3, radioButton4, radioButton5, radioButton6, 6);
            enableTextFields(fourthAnswerTextField, fifthAnswerTextField, sixthAnswerTextField, 6);
            enableCheckBoxes(correct4, correct5, correct6, 6);
        }
        enableMCOptionsPanel(false);
        enableQuestionsPanel(true);
    }

    public int getCorrectScore() {
        return mcItemSet.getPuntuation();
    }

    public void reset() {
        radioButton3.setSelected(false);
        radioButton4.setSelected(true);
        radioButton5.setSelected(false);
        radioButton6.setSelected(false);
        questionsQuantityTextField.setText("10");
        fixedPunctuationField.setText("10");
        substractProportionalityTextField.setText("0.5");
        fixedPunctuationCheckBox.setSelected(false);
        oneAnswerPerQuestionCheckBox.setSelected(true);
        clearAllFields();
        enableMCOptionsPanel(true);
        enableQuestionsPanel(false);
        mcItemSet = new MCItemSet();
        questionsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
                textBundle.getString(TextBundleEnum.CREAR_PREGUNTA.toString()) +
                        " " + (mcItemSet.getMCItems().size() + 1) + " " +
                        textBundle.getString(TextBundleEnum.DE.toString()) + " " +
                        questionsQuantityTextField.getText()));
        fixedPunctuationField.setEditable(false);
        fullQuestionaireTextArea.setText("");
    }

    /**
     * Habilita o desabilita los checkboxes;
     *
     * @param box4;
     * @param box5;
     * @param box6;
     * @param questions - cantidad de preguntas;
     */
    private static void enableCheckBoxes(JCheckBox box4, JCheckBox box5, JCheckBox box6, int questions) {
        box4.setEnabled(false);
        box5.setEnabled(false);
        box6.setEnabled(false);
        switch (questions) {
            case 6:
                box6.setEnabled(true);
            case 5:
                box5.setEnabled(true);
            case 4:
                box4.setEnabled(true);
        }
    }

    /**
     * Desabilita los textfields;
     *
     * @param textField4;
     * @param textField5;
     * @param textField6;
     * @param questions   - cantidad de preguntas;
     */
    private static void enableTextFields(JTextField textField4, JTextField textField5, JTextField textField6, int questions) {
        textField4.setEnabled(false);
        textField5.setEnabled(false);
        textField6.setEnabled(false);
        switch (questions) {
            case 6:
                textField6.setEnabled(true);
            case 5:
                textField5.setEnabled(true);
            case 4:
                textField4.setEnabled(true);


        }
    }

    /**
     * Selecciona el radioButton que corresponde a la cantidad de respuestas propias de la pregunta;
     *
     * @param radioButton3;
     * @param radioButton4;
     * @param radioButton5;
     * @param radioButton6;
     * @param questions-    cantidad de preguntas;
     */
    private static void setSelectedRadioButtons(JRadioButton radioButton3, JRadioButton radioButton4,
                                                JRadioButton radioButton5, JRadioButton radioButton6, int questions) {
        radioButton3.setSelected(false);
        radioButton4.setSelected(false);
        radioButton5.setSelected(false);
        radioButton6.setSelected(false);
        switch (questions) {
            case 3:
                radioButton3.setSelected(true);
                break;
            case 4:
                radioButton4.setSelected(true);
                break;
            case 5:
                radioButton5.setSelected(true);
                break;
            case 6:
                radioButton6.setSelected(true);
                break;
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setContentPane(new CreateMChoicePanel(new JButton(), new JButton(), new JFileChooser()));
        frame.setSize(new Dimension(500, 500));
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    protected void setSaveActionListener() {
        class SaveMCAction extends AbstractAction {
            public SaveMCAction() {
                super("", Utiles.createImageIcon(URLEnum.getReference(URLEnum.SAVE_AS)));
            }

            public void actionPerformed(ActionEvent e) {
                String path = "";
                if (mcItemSet.getMCItems().size() > 0) {
                    int state = fileChooser.showSaveDialog(JOptionPane.getRootFrame());
                    if (state == JFileChooser.APPROVE_OPTION) {
                        path = fileChooser.getSelectedFile().getPath();
                        try {
                            Utiles.serialize(getExercise(), Utiles.getFilePathWithExtension(path, ".mcf"));//.mcf=multiple choice file;
                        } catch (ExerciseNotBuiltException e1) {
                            e1.printStackTrace();
                        } catch (PunctuationZeroException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        }
        saveButton.setAction(new SaveMCAction());
    }

    protected void setSaveButtonEnabled() {
        saveButton.setEnabled(true);
    }

    protected void setOpenActionListener() {
        class OpenMCAction extends AbstractAction {
            public OpenMCAction() {
                super("", Utiles.createImageIcon(URLEnum.getReference(URLEnum.OPEN)));
            }

            public void actionPerformed(ActionEvent e) {
                String path = "";
                int state = fileChooser.showOpenDialog(JOptionPane.getRootFrame());
                if (state == JFileChooser.APPROVE_OPTION) {
                    path = fileChooser.getSelectedFile().getPath();
                    TestExcercise testExcercise = Utiles.deserialize(path);
                    setExercise(testExcercise);
                }
            }
        }
        openButton.setAction(new OpenMCAction());
    }

    protected void setOpenButtonEnabled() {
        openButton.setEnabled(true);
    }

    protected void setFocusOnComponent() {
        //todo completar
    }
}
